// 当前页
var CURR_PAGE = 1;
// 当前显示的页面
var CURR_SHOW_PAGE_ID;
// 当前类型
var CURR_TYPE;
// 线路名称长度
var WORKLINE_NAME_LENGTH = 50;
// 线路名称长度限制
var WORKLINE_NAME_LENGTH_SHOW = 27;

/** ------------------iScroll上拉事件相关----------------------------------- */
var dataScroll, pullUpEl, pullUpOffset;

/**
 * 上拉事件
 */
var pullUpAction = function() {

	++CURR_PAGE;
	queryDataByType()

	// 刷新
	dataScroll.refresh();
};

/**
 * 初始化iScroll控件
 */
function loaded() {

	pullUpEl = $('#pullup');
	pullUpOffset = pullUpEl.attr("offsetHeight");

	dataScroll = new iScroll('wrapper', {
				scrollbarClass : 'myScrollbar', /* 重要样式 */
				useTransition : false,
				onRefresh : function() {
					if (pullUpEl.hasClass('loading')) {
						pullUpEl.removeClass('loading');
						$('.pullup-label', pullUpEl).html('上拉加载更多...');
					}
				},
				onScrollMove : function() {
					if (this.y > 0) {
						pullUpEl.removeClass('flip');
						return;
					}

					if (this.y < (this.maxScrollY - 5)
							&& !pullUpEl.hasClass('flip')) {
						pullUpEl.removeClass();
						pullUpEl.addClass('flip');
						$('.pullup-label', pullUpEl).html('松手开始更新...');
						this.maxScrollY = this.maxScrollY;
					} else if (this.y > (this.maxScrollY + 5)
							&& pullUpEl.hasClass('flip')) {
						pullUpEl.removeClass();
						$('.pullup-label', pullUpEl).html('上拉加载更多...');
						this.maxScrollY = pullUpOffset;
					}
				},
				onScrollEnd : function() {
					if (pullUpEl.hasClass('flip')) {
						pullUpEl.removeClass();
						pullUpEl.addClass('loading');
						$('.pullup-label', pullUpEl).html('加载中...');
						pullUpAction();
					}
				}
			});
}
/** ----------------------------------------------------- */

/**
 * 根据类别查询数据
 */
var queryDataByType = function(isQuery) {

	var params = "{"
	params += "'page': '" + CURR_PAGE + "'";
	if (null == isQuery || undefined == isQuery || false == isQuery) {
		params += ", 'isQuery': 'false'";
	} else {
		params += ", 'isQuery': 'true'";
	}

	var pId = $("#parentid").val();
	if (null != pId && pId.trim().length > 0) {
		params += ", 'pId': '" + pId + "'";
	}
	try {
		if ("scheme" == CURR_TYPE) {
			var schemeName = $("#schemename", $("#funccontent")).val();
			if (schemeName.trim().length > 0) {
				params += ", 'schemename': '" + schemeName + "'";
			}
			params += "}";
			window.schemejsi.querySchemesByPage(params);
		} else if ("workline" == CURR_TYPE) {
			var lineName = $("#linename", $("#funccontent")).val();
			if (lineName.trim().length > 0) {
				params += ", 'linename': '" + lineName + "'";
			}
			params += "}";
			window.worklinejsi.queryWorkLinesByPage(params);
		} else if ("terminal" == CURR_TYPE) {
			var terminalAddr = $("#terminaladdr", $("#funccontent")).val();
			if (terminalAddr.trim().length > 0) {
				params += ", 'terminaladdr': '" + terminalAddr + "'";
			}
			params += "}";
			window.terminaljsi.queryTerminalsByPage(params);
		} else if ("indicator" == CURR_TYPE) {
			var indicatorAddr = $("#indicatoraddr", $("#funccontent")).val();
			if (indicatorAddr.trim().length > 0) {
				params += ", 'indicatoraddr': '" + indicatorAddr + "'";
			}
			params += "}";
			window.indicatorjsi.queryIndicatorsByPage(params);
		}
	} catch (e) {
	}
};

/**
 * 方案管理
 */
var scheme = function() {

	backToolbar();

	$("#schemename", $("#funccontent")).val("");
	initPage("方案管理", "scheme");

	CURR_PAGE = 1;

	// 清空
	$("tbody", $("#schemetable")).empty();

	queryDataByType();

	$("#schemequerybtn").unbind().bind("tap", function() {
				// 清空
				$("tbody", $("#schemetable")).empty();

				CURR_PAGE = 1;
				queryDataByType(true);
			});
};

/**
 * 页面初始化
 * 
 * @param {}
 *            title
 * @param {}
 *            type
 */
var initPage = function(title, type) {
	$("#navfunctitle").html(title);
	$("#" + CURR_SHOW_PAGE_ID).hide();

	CURR_TYPE = type;
	CURR_SHOW_PAGE_ID = CURR_TYPE + "content";
	$("#" + CURR_SHOW_PAGE_ID).show();
};

// 当前操作的TR
var CURR_DATA_TR;
/**
 * 分页查询方案的回调函数
 * 
 * @param {}
 *            data
 */
var querySchemesByPageCallback = function(data) {

	var currTable = $("#schemetable");
	if (1 == CURR_PAGE) {
		// 清空
		$("tbody", currTable).empty();
	}
	for (var i = 0; i < data.length; i++) {
		var tr = "<tr><td>" + data[i]._id + "</td><td>" + data[i].schemename
				+ "</td>" + "<td>" + data[i].time + "</td></tr>";
		$("tbody", currTable).append(tr);
	}

	// 刷新，关键重构是列与列头的关系
	currTable.table("refresh");

	$("tbody tr", currTable).bind("taphold", function() {

		backToolbar();

		CURR_DATA_TR = $(this);
		var id = $("td:first-child", CURR_DATA_TR).html();
		// 默认方案不能编辑
		if (1 == id) {
			$("#dataeditdiv")
					.html('<a data-role="button" id="nextstepbtn" data-icon="arrow-r" data-inline="true" data-theme="f" data-iconpos="notext"></a>');
			$("a", "#dataeditdiv").trigger('create').buttonMarkup("refresh");
			CURR_DATA_TR.addClass("tr-selected");
			showMsg("默认方案不可编辑!", 3000);
			return;
		}

		CURR_DATA_TR.addClass("tr-selected");

		$("#dataeditdiv")
				.html('<a data-role="button" id="nextstepbtn" data-icon="arrow-r" data-inline="true" data-theme="f" data-iconpos="notext"></a>'
						+ '<a data-role="button" id="modifybtn" data-icon="edit" data-inline="true" data-theme="f" data-iconpos="notext">修改</a>'
						+ '<a data-role="button" id="removebtn" data-icon="delete" data-inline="true" data-theme="f" data-iconpos="notext">删除</a>'
						+ '<a data-role="button" id="backbtn" data-icon="back" data-inline="true" data-theme="f" data-iconpos="notext">取消</a>');
		$("a", "#dataeditdiv").trigger('create').buttonMarkup("refresh");
	});
}

/*
 * 新增按钮绑定的事件
 */
var add = function(e) {
	if ("scheme" == CURR_TYPE) {
		// 打开新增方案的对话框
		$("#schemepopup").trigger("create").popup("open");
		$(".tipcontentspan", $("#schemepopup")).html("");
		$("#_id", $("#schemepopup")).val("");
		$("#schemename", $("#schemepopup")).val("");
		$("#schemename", $("#schemepopup")).focus();
		$("#schemeoperspan").html("添加");
		$(".ui-btn-text", $("#schemeeditbtn")).html("添加");
		$("#schemeeditbtn").unbind("click").bind("click", editScheme);
		return false;
	} else if ("workline" == CURR_TYPE) {
		// 打开新增线路的对话框
		$("#worklinepopup").trigger("create").popup("open");
		$(".tipcontentspan", $("#worklinepopup")).html("");
		$("#_id", $("#worklinepopup")).val("");
		$("#linename", $("#worklinepopup")).val("");
		$("#schemeid", $("#worklinepopup")).val("-1").selectmenu("refresh");
		$("#linename", $("#worklinepopup")).focus();
		$("#worklineoperspan").html("添加");
		$(".ui-btn-text", $("#worklineeditbtn")).html("添加");
		$("#worklineeditbtn").unbind("click").bind("click", editWorkLine);
	} else if ("terminal" == CURR_TYPE) {
		// 打开新增终端的对话框
		$("#terminalpopup").trigger("create").popup("open");
		$(".tipcontentspan", $("#terminalpopup")).html("");
		$("#lineid", $("#terminalpopup")).val("-1").selectmenu("refresh");
		$("#_id", $("#terminalpopup")).val("");
		$("#terminaladdr", $("#terminalpopup")).val("");
		// $("#terminaladdr", $("#terminalpopup")).textinput("enable");
		$("#wirelessaddr", $("#terminalpopup")).val("");
		$("#location", $("#terminalpopup")).val("");
		$("#terminaladdr", $("#terminalpopup")).focus();
		$("#terminaloperspan").html("添加");
		$(".ui-btn-text", $("#terminaleditbtn")).html("添加");
		$("#terminalvirtualbtn").show();

		$("#terminaleditbtn").unbind().bind("click", editTerminal);
		// 虚拟终端按钮绑定事件
		$("#terminalvirtualbtn").unbind().bind("tap", virtualTerminal);
		// 终端清空按钮绑定事件
		$("#terminalclearbtn").unbind().bind("tap", clearTerminal);
	}
};

/**
 * 编辑方案（新增或修改）
 */
var editScheme = function() {

	var _id = $("#_id", $("#schemepopup")).val();
	var schemename = $("#schemename", $("#schemepopup")).val();

	$(".tipcontentspan", $("#schemepopup")).html("");
	var msg = "";
	if (0 == schemename.trim().length) {
		msg = "方案名称不能为空!";
		$(".tipcontentspan", $("#schemepopup")).html(msg);
		$("#schemename", $("#schemepopup")).focus();
		return false;
	}
	if (30 < schemename.strLen()) {
		msg = "方案名称的长度不能超过30个字符!";
		$(".tipcontentspan", $("#schemepopup")).html(msg);
		$("#schemename", $("#schemepopup")).focus();
		return false;
	}

	var params = "{";
	if (null != _id && undefined != _id && 0 < _id.length) {
		params += "'_id': '" + _id + "',";
	}
	params += "'schemename': '" + schemename + "'";
	params += "}";
	window.schemejsi.addOrModifyScheme(params);
};

/**
 * 编辑的回调方法
 */
var editSuccessCallback = function(data) {
	var type = data.type;
	if (type) {
		if ("scheme" == type) {
			$("#schemepopup").popup("close");
			$("tbody", $("#schemetable")).empty();
			backToolbar();
		} else if ("workline" == type) {
			$("#worklinepopup").popup("close");
			$("tbody", $("#worklinetable")).empty();
			backToolbar();
		} else if ("terminal" == type) {
			$("#terminalpopup").popup("close");
			$("tbody", $("#terminaltable")).empty();
			backToolbar();
		} else if ("indicator" == type) {
			$("#indicatorpopup").popup("close");
			$("tbody", $("#indicatortable")).empty();

			CURR_DATA_TR.removeClass("tr-selected");
			CURR_DATA_TR = null;
			$("#dataeditdiv").html("");
		}
	}

	// 刷新
	CURR_PAGE = 1;
	queryDataByType(true);
};

/**
 * 取消工具栏
 * 
 * @return {Boolean}
 */
var backToolbar = function() {

	if (CURR_DATA_TR) {
		CURR_DATA_TR.removeClass("tr-selected");
		CURR_DATA_TR = null;
	}
	$("#dataeditdiv")
			.html('<a data-role="button" id="addbtn" data-icon="plus" data-inline="true" data-theme="f" data-iconpos="notext">添加</a>');
	$("a", "#dataeditdiv").trigger('create').buttonMarkup("refresh");
	return false;
};

/**
 * 编辑线路（新增或修改）
 */
var editWorkLine = function() {
	var _id = $("#_id", $("#worklinepopup")).val();
	var linename = $("#linename", $("#worklinepopup")).val();
	var remark = $("#remark", $("#worklinepopup")).val();
	var schemeid = $("#schemeid", $("#worklinepopup")).val();

	$(".tipcontentspan", $("#worklinepopup")).html("");

	var msg = "";
	if (0 == linename.trim().length) {
		msg = "线路名称不能为空!";
		$(".tipcontentspan", $("#worklinepopup")).html(msg);
		$("#linename", $("#worklinepopup")).focus();
		return false;
	}

	if (WORKLINE_NAME_LENGTH < linename.strLen()) {
		msg = "线路名称的长度不能超过" + WORKLINE_NAME_LENGTH + "个字符!";
		$(".tipcontentspan", $("#worklinepopup")).html(msg);
		$("#linename", $("#worklinepopup")).focus();
		return false;
	}

	if (-1 == schemeid) {
		msg = "所属方案不能为空!";
		$(".tipcontentspan", $("#worklinepopup")).html(msg);
		$("#schemeid", $("#worklinepopup")).focus();
		return false;
	}

	var params = "{";
	if (null != _id && undefined != _id && 0 < _id.length) {
		params += "'_id': '" + _id + "',";
	}
	params += "'linename': '" + linename + "',";
	params += "'schemeid': '" + schemeid + "',";
	params += "'remark': '" + remark + "'";
	params += "}";

	window.worklinejsi.addOrModifyWorkLine(params);
};

/**
 * 编辑终端（新增或修改）
 */
var editTerminal = function() {
	var _id = $("#_id", $("#terminalpopup")).val();
	var terminaladdr = $("#terminaladdr", $("#terminalpopup")).val();
	var wirelessaddr = $("#wirelessaddr", $("#terminalpopup")).val();
	var lineid = $("#lineid", $("#terminalpopup")).val();
	var location = $("#location", $("#terminalpopup")).val();

	$(".tipcontentspan", $("#terminalpopup")).html("");

	var msg = "";
	if (0 == terminaladdr.trim().length) {
		msg = "终端地址不能为空!";
		$(".tipcontentspan", $("#terminalpopup")).html(msg);
		$("#terminaladdr", $("#terminalpopup")).focus();
		return false;
	}

	if (8 != terminaladdr.length) {
		msg = "终端地址的长度错误, 长度为8个字符!";
		$(".tipcontentspan", $("#terminalpopup")).html(msg);
		$("#terminaladdr", $("#terminalpopup")).focus();
		return false;
	}

	if (0 == wirelessaddr.trim().length) {
		msg = "无线模块地址不能为空!";
		$(".tipcontentspan", $("#terminalpopup")).html(msg);
		$("#wirelessaddr", $("#terminalpopup")).focus();
		return false;
	}

	if (6 != wirelessaddr.length) {
		msg = "无线模块地址的长度错误, 长度为6个字符!";
		$(".tipcontentspan", $("#terminalpopup")).html(msg);
		$("#wirelessaddr", $("#terminalpopup")).focus();
		return false;
	}

	if (-1 == lineid) {
		msg = "所属线路不能为空!";
		$(".tipcontentspan", $("#terminalpopup")).html(msg);
		$("#lineid", $("#terminalpopup")).focus();
		return false;
	}

	var params = "{";
	if (null != _id && undefined != _id && 0 < _id.length) {
		params += "'_id': '" + _id + "',";
	}
	params += "'terminaladdr': '" + terminaladdr + "',";
	params += "'wirelessaddr': '" + wirelessaddr + "',";
	params += "'lineid': '" + lineid + "',";
	params += "'location': '" + location + "'";
	params += "}";

	window.terminaljsi.addOrModifyTerminal(params);
};

// 分支号和级数原始值
var OLD_BRANCH;
var OLD_LEVEL;
/**
 * 编辑指示器（新增或修改）
 */
var editIndicator = function() {
	var _id = $("#_id", $("#indicatorpopup")).val();
	var branch = $("#branch", $("#indicatorpopup")).val();
	var level = $("#level", $("#indicatorpopup")).val();
	var gpsx = $("#gpsx", $("#indicatorpopup")).val();
	var gpsy = $("#gpsy", $("#indicatorpopup")).val();
	var location = $("#location", $("#indicatorpopup")).val();

	$(".tipcontentspan", $("#indicatorpopup")).html("");

	var msg = "";
	if (0 != OLD_BRANCH && 0 == branch.trim().length) {
		msg = "分支号不能修改为空!";
		$(".tipcontentspan", $("#indicatorpopup")).html(msg);
		$("#branch", $("#indicatorpopup")).focus();
		return false;
	}

	if (-1 != OLD_LEVEL && 0 != OLD_LEVEL && -1 == level) {
		msg = "级数不能修改为空!";
		$(".tipcontentspan", $("#indicatorpopup")).html(msg);
		$("#level", $("#indicatorpopup")).focus();
		return false;
	}

	if (30 < location.strLen()) {
		msg = "安装位置不能超过30个字符!";
		$(".tipcontentspan", $("#indicatorpopup")).html(msg);
		$("#location", $("#indicatorpopup")).focus();
		return false;
	}

	try {
		var params = "{";
		if (null != _id && undefined != _id && 0 < _id.length) {
			params += "'_id': '" + _id + "',";
		}
		params += "'branch': '" + branch + "',";
		params += "'level': '" + level + "',";
		params += "'gpsx': '" + gpsx + "',";
		params += "'gpsy': '" + gpsy + "',";
		params += "'location': '" + location + "'";
		params += "}";
		window.indicatorjsi.addOrModifyIndicator(params);
	} catch (e) {
	}
};

/*
 * 进入下一阶段按钮绑定的事件
 */
var nextStep = function() {

	var _id = $("td:first-child", CURR_DATA_TR).html();
	try {
		$("#parentid").val(_id);

		if ("scheme" == CURR_TYPE) {
			CURR_TYPE = "workline";
			workLine();
			$(".ui-btn-active", $("#funcsmenu")).removeClass("ui-btn-active");
			$("#worklinebtn").parent().addClass("ui-btn-active");
		} else if ("workline" == CURR_TYPE) {
			CURR_TYPE = "terminal";
			terminal();
			$(".ui-btn-active", $("#funcsmenu")).removeClass("ui-btn-active");
			$("#terminalbtn").parent().addClass("ui-btn-active");
		} else if ("terminal" == CURR_TYPE) {
			CURR_TYPE = "indicator";
			indicator();
			$(".ui-btn-active", $("#funcsmenu")).removeClass("ui-btn-active");
			$("#indicatorbtn").parent().addClass("ui-btn-active");
		}
	} catch (e) {
	}
};

/*
 * 修改按钮绑定的事件
 */
var modify = function() {

	//$("#parentid").val("");
	var _id = $("td:first-child", CURR_DATA_TR).html();
	try {
		var params = "{";
		if (null != _id && undefined != _id && 0 < _id.length) {
			params += "'_id': '" + _id + "'";
		}
		params += "}";
		if ("scheme" == CURR_TYPE) {
			window.schemejsi.querySchemes(params);
		} else if ("workline" == CURR_TYPE) {
			window.worklinejsi.queryWorkLines(params);
		} else if ("terminal" == CURR_TYPE) {
			window.terminaljsi.queryTerminals(params);
		} else if ("indicator" == CURR_TYPE) {
			window.indicatorjsi.queryIndicators(params);
		}
	} catch (e) {
	}
};

/**
 * 方案修改，加载方案的原始信息
 */
var loadSchemes = function(json) {
	var flag = json.flag;
	var data = json.list;
	if ("query" == flag) { // 如果当前页在线路管理，则加载所属方案下拉框
		var options = "<option value='-1'>- 请选择 -</option>";
		for (var i = 0; i < data.length; i++) {
			options += "<option value='" + data[i]._id + "'>"
					+ data[i].schemename + "</option>";
		}
		$("#schemeid", $("#worklinepopup")).html(options);
		$("#schemeid", $("#worklinepopup")).selectmenu("refresh");
	} else if ("modify" == flag) {

		// 打开修改方案的对话框
		$("#schemepopup").trigger("create").popup("open");
		$(".tipcontentspan", $("#schemepopup")).html("");

		$("#_id", $("#schemepopup")).val(data[0]._id);
		$("#schemename", $("#schemepopup")).val(data[0].schemename);

		$("#schemeoperspan").html("修改");
		$(".ui-btn-text", $("#schemeeditbtn")).html("修改");
		$("#schemeeditbtn").unbind("click").bind("click", editScheme);
	}
};

/**
 * 线路修改，加载线路的原始信息
 */
var loadWorkLines = function(json) {

	var flag = json.flag;
	var data = json.list;
	if ("query" == flag) { // 如果当前页在线路管理，则加载所属方案下拉框
		var options = "<option value='-1'>- 请选择 -</option>";
		for (var i = 0; i < data.length; i++) {
			var lineName = data[i].linename;
			if (lineName.strLen() > WORKLINE_NAME_LENGTH_SHOW - 3) {
				lineName = lineName.substring(0, WORKLINE_NAME_LENGTH_SHOW - 3)
						+ "...";
			}

			options += "<option value='" + data[i]._id + "'>" + lineName
					+ "</option>";
		}
		$("#lineid", $("#terminalpopup")).html(options);
		$("#lineid", $("#terminalpopup")).selectmenu("refresh");
	} else if ("modify" == flag) {

		// 打开修改线路的对话框
		$("#worklinepopup").trigger("create").popup("open");
		$(".tipcontentspan", $("#worklinepopup")).html("");

		$("#_id", $("#worklinepopup")).val(data[0]._id);
		$("#linename", $("#worklinepopup")).val(data[0].linename);
		$("#remark", $("#worklinepopup")).val(data[0].remark);
		$("#schemeid", $("#worklinepopup")).val(data[0].schemeid)
				.selectmenu("refresh");

		$("#worklineoperspan").html("修改");
		$(".ui-btn-text", $("#worklineeditbtn")).html("修改");

		$("#worklineeditbtn").unbind("click").bind("click", editWorkLine);
	}
};

/**
 * 终端修改，加载终端的原始信息
 */
var loadTerminals = function(json) {

	// 打开修改终端的对话框
	$("#terminalpopup").trigger("create").popup("open");
	$(".tipcontentspan", $("#terminalpopup")).html("");

	$("#_id", $("#terminalpopup")).val(json[0]._id);
	$("#terminaladdr", $("#terminalpopup")).val(json[0].terminaladdr);
	// $("#terminaladdr", $("#terminalpopup")).textinput("disable");
	$("#wirelessaddr", $("#terminalpopup")).val(json[0].wirelessaddr);
	$("#location", $("#terminalpopup")).val(json[0].location);
	$("#lineid", $("#terminalpopup")).val(json[0].lineid).selectmenu("refresh");

	$("#terminaloperspan").html("修改");
	$(".ui-btn-text", $("#terminaleditbtn")).html("修改");
	$("#terminalvirtualbtn").hide();

	$("#terminaleditbtn").unbind().bind("tap", editTerminal);
	// 终端清空按钮绑定事件
	$("#terminalclearbtn").unbind().bind("tap", clearTerminal);
};

/**
 * 动态加载台账树的回调方法，显示台账树，并对树上的节点动态绑定方法（长按和点击事件）
 */
var loadIndicators = function(json) {

	OLD_BRANCH = 0;
	OLD_LEVEL = -1;

	// 打开修改终端的对话框
	$("#indicatorpopup").trigger("create").popup("open");
	$(".tipcontentspan", $("#indicatorpopup")).html("");

	var branch = json[0].branch;
	branch = branch == undefined ? 0 : branch;
	var level = json[0].level;
	level = level == undefined ? -1 : level;

	$("#_id", $("#indicatorpopup")).val(json[0]._id);
	$("#indicatoraddr", $("#indicatorpopup")).val(json[0].indicatoraddr);
	$("#indicatoraddr", $("#indicatorpopup")).textinput("disable");
	$("#phase", $("#indicatorpopup")).val(json[0].phase).selectmenu("refresh");
	$("#phase", $("#indicatorpopup")).selectmenu("disable");
	$("#gpsx", $("#indicatorpopup")).val(json[0].gpsx);
	$("#gpsy", $("#indicatorpopup")).val(json[0].gpsy);
	$("#branch", $("#indicatorpopup")).val(json[0].branch);
	$("#level", $("#indicatorpopup")).val(json[0].level).selectmenu("refresh");
	$("#location", $("#indicatorpopup")).val(json[0].location);

	OLD_BRANCH = branch;
	OLD_LEVEL = level;

	$("#indicatoroperspan").html("修改");
	$(".ui-btn-text", $("#indicatoreditbtn")).html("修改");

	$("#indicatoreditbtn").unbind().bind("click", editIndicator);
};

/*
 * 删除按钮绑定的事件
 */
var remove = function() {
	// 打开删除方案的对话框
	$("#removeconfirmpopup").trigger("create").popup("open");

	//$("#parentid").val("");
	var id = $("td:first-child", CURR_DATA_TR).html();
	$("#_id", $("#removeconfirmpopup")).val(id);

	if ("scheme" == CURR_TYPE) {
		$("#removetypespan").html("方案");
	} else if ("workline" == CURR_TYPE) {
		$("#removetypespan").html("线路");
	} else if ("terminal" == CURR_TYPE) {
		$("#removetypespan").html("终端");
	} else if ("indicator" == CURR_TYPE) {
		$("#removetypespan").html("指示器");
	}

	// 删除确认对话框按钮绑定事件
	$("#removeyesbtn").unbind("click").bind("click", doRemove);
};

/**
 * 删除提交
 */
var doRemove = function() {
	var _id = $("#_id", $("#removeconfirmpopup")).val();

	if ("scheme" == CURR_TYPE) {
		window.schemejsi.removeScheme(_id + "");
	} else if ("workline" == CURR_TYPE) {
		window.worklinejsi.removeWorkLine(_id + "");
	} else if ("terminal" == CURR_TYPE) {
		window.terminaljsi.removeTerminal(_id + "");
	} else if ("indicator" == CURR_TYPE) {
		window.indicatorjsi.removeIndicator(_id + "");
	}
};

/**
 * 删除成功的回调方法
 */
var removeSuccuessCallback = function(data) {

	// 关闭删除确认对话框
	$("#removeconfirmpopup").popup("close");
	if ("scheme" == CURR_TYPE) {
		$("tbody", $("#schemetable")).empty();
	} else if ("workline" == CURR_TYPE) {
		$("tbody", $("#worklinetable")).empty();
	} else if ("terminal" == CURR_TYPE) {
		$("tbody", $("#terminaltable")).empty();
	} else if ("indicator" == CURR_TYPE) {
		$("tbody", $("#indicatortable")).empty();
	}

	CURR_PAGE = 1;
	queryDataByType(true);

	backToolbar();
};

/**
 * 停止删除的回调方法
 */
var removePauseCallback = function() {
	// 关闭删除确认对话框
	$("#removeconfirmpopup").popup("close");
};

/**
 * 线路管理
 */
var workLine = function() {

	backToolbar();

	initPage("线路管理", "workline");
	$("#linename", $("#funccontent")).val("");

	CURR_PAGE = 1;

	// 清空
	$("tbody", $("#worklinetable")).empty();

	queryDataByType();

	$("#worklinequerybtn").unbind().bind("tap", function() {
				// 清空
				$("tbody", $("#worklinetable")).empty();
				CURR_PAGE = 1;
				queryDataByType(true);
			});

	// 异步加载所属方案下拉列表
	try {
		window.schemejsi.querySchemes("");
	} catch (e) {
	}
};

/**
 * 分页查询线路的回调函数
 * 
 * @param {}
 *            data
 */
var queryWorkLinesByPageCallback = function(data) {

	var currTable = $("#worklinetable");

	if (1 == CURR_PAGE) {
		// 清空
		$("tbody", currTable).empty();
	}
	for (var i = 0; i < data.length; i++) {
		var lineName = data[i].linename;
		if (lineName.strLen() > WORKLINE_NAME_LENGTH_SHOW - 3) {
			lineName = lineName.substring(0, WORKLINE_NAME_LENGTH_SHOW - 3)
					+ "...";
		}
		var tr = "<tr><td>" + data[i]._id + "</td><td>" + lineName + "</td>"
				+ "<td>"
				+ (data[i].schemename == undefined ? "" : data[i].schemename)
				+ "</td><td>" + data[i].time + "</td></tr>";
		$("tbody", currTable).append(tr);
	}

	// 刷新，关键重构是列与列头的关系
	currTable.table("refresh");

	$("tbody tr", currTable).bind("taphold", function() {
		backToolbar();

		CURR_DATA_TR = $(this);
		CURR_DATA_TR.addClass("tr-selected");

		$("#dataeditdiv")
				.html('<a data-role="button" id="nextstepbtn" data-icon="arrow-r" data-inline="true" data-theme="f" data-iconpos="notext"></a>'
						+ '<a data-role="button" id="modifybtn" data-icon="edit" data-inline="true" data-theme="f" data-iconpos="notext">修改</a>'
						+ '<a data-role="button" id="removebtn" data-icon="delete" data-inline="true" data-theme="f" data-iconpos="notext">删除</a>'
						+ '<a data-role="button" id="backbtn" data-icon="back" data-inline="true" data-theme="f" data-iconpos="notext">取消</a>');
		$("a", "#dataeditdiv").trigger('create').buttonMarkup("refresh");
	});
}

/**
 * 终端管理
 */
var terminal = function() {

	backToolbar();

	initPage("终端管理", "terminal");
	$("#terminaladdr", $("#funccontent")).val("");

	CURR_PAGE = 1;

	// 清空
	$("tbody", $("#terminaltable")).empty();

	queryDataByType();

	$("#terminalquerybtn").unbind().bind("tap", function() {
				// 清空
				$("tbody", $("#terminaltable")).empty();
				CURR_PAGE = 1;
				queryDataByType(true);
			});

	// 导出Excel
	$("#terminalexportbtn").unbind().bind("tap", function() {

				var params = "{"
				var terminalAddr = $("#terminaladdr").val();
				if (terminalAddr.trim().length > 0) {
					params += "'terminaladdr': '" + terminalAddr + "'";
				}
				params += "}";

				try {
					window.terminaljsi.exportTerminals(params);
				} catch (e) {
				}
			});

	// 异步加载所属方案下拉列表
	try {
		window.worklinejsi.queryWorkLines("");
	} catch (e) {
	}
};

/**
 * 分页查询終端的回调函数
 * 
 * @param {}
 *            data
 */
var queryTerminalsByPageCallback = function(data) {

	var currTable = $("#terminaltable");

	if (1 == CURR_PAGE) {
		// 清空
		$("tbody", currTable).empty();
	}
	for (var i = 0; i < data.length; i++) {
		var lineName = data[i].linename;
		if (lineName.strLen() > WORKLINE_NAME_LENGTH_SHOW - 3) {
			lineName = lineName.substring(0, WORKLINE_NAME_LENGTH_SHOW - 3)
					+ "...";
		}

		var location = data[i].location;
		if (location.strLen() > 20 - 3) {
			location = location.substring(0, 20 - 3) + "...";
		}
		var tr = "<tr><td>" + data[i]._id + "</td><td>" + data[i].terminaladdr
				+ "</td>" + "<td>" + data[i].wirelessaddr + "</td><td>"
				+ location + "</td><td>" + lineName + "</td><td>"
				+ data[i].time + "</td></tr>";
		$("tbody", currTable).append(tr);
	}

	// 刷新，关键重构是列与列头的关系
	currTable.table("refresh");

	$("tbody tr", currTable).bind("taphold", function() {
		backToolbar();

		CURR_DATA_TR = $(this);
		CURR_DATA_TR.addClass("tr-selected");

		$("#dataeditdiv")
				.html('<a data-role="button" id="nextstepbtn" data-icon="arrow-r" data-inline="true" data-theme="f" data-iconpos="notext"></a>'
						+ '<a data-role="button" id="modifybtn" data-icon="edit" data-inline="true" data-theme="f" data-iconpos="notext">修改</a>'
						+ '<a data-role="button" id="removebtn" data-icon="delete" data-inline="true" data-theme="f" data-iconpos="notext">删除</a>'
						+ '<a data-role="button" id="backbtn" data-icon="back" data-inline="true" data-theme="f" data-iconpos="notext">取消</a>');
		$("a", "#dataeditdiv").trigger('create').buttonMarkup("refresh");
	});
}

/**
 * 虚拟终端按钮绑定事件
 */
var virtualTerminal = function() {

	// 获取所有的实施方案树上的所有终端
	var terminals = $("tbody tr", $("#terminaltable"));
	// 获取后4位最大值
	var max = 0;
	for (var i = 0; i < terminals.length; i++) {
		var terminalAddr = $("td:nth-child(2)", terminals[i]).html();
		var tempNum = terminalAddr.substring(4);

		if (max < parseInt(tempNum, 16)) {
			max = parseInt(tempNum, 16);
		}
	}

	// 最大值+1
	max++;

	// 转成4位16进制数
	var strNum;
	strNum = max.toString(16);

	var len = strNum.length;
	for (var i = 4; i > len; i--) {
		strNum = "0" + strNum;
	}

	$("#terminaladdr", $("#terminalpopup")).val("TERM" + strNum);
	$("#wirelessaddr", $("#terminalpopup")).val("V12345");
	$("#lineid", $("#terminalpopup")).val("-1").selectmenu("refresh");
	$("#location", $("#terminalpopup")).val("");

};

/**
 * 清空表單內容
 */
var clearTerminal = function() {

	var id = $("#_id", $("#terminalpopup")).val();
	$("#terminaladdr", $("#terminalpopup")).val("");
	$("#wirelessaddr", $("#terminalpopup")).val("");
	$("#lineid", $("#terminalpopup")).val("-1").selectmenu("refresh");
	$("#location", $("#terminalpopup")).val("");
};

/**
 * 指示器管理
 */
var indicator = function() {

	$("#dataeditdiv").html('');

	initPage("指示器管理", "indicator");
	$("#indicatoraddr", $("#funccontent")).val("");

	CURR_PAGE = 1;

	// 清空
	$("tbody", $("#indicatortable")).empty();

	queryDataByType();

	$("#indicatorquerybtn").unbind().bind("tap", function() {
				// 清空
				$("tbody", $("#indicatortable")).empty();
				CURR_PAGE = 1;
				queryDataByType(true);
			});

	// 导出Excel
	$("#indicatorexportbtn").unbind().bind("tap", function() {

				var params = "{"
				var indicatorAddr = $("#indicatoraddr").val();
				if (indicatorAddr.trim().length > 0) {
					params += "'indicatoraddr': '" + indicatorAddr + "'";
				}
				params += "}";

				try {
					window.indicatorjsi.exportIndicators(params);
				} catch (e) {
				}
			});
};

/**
 * 分页查询指示器的回调函数
 * 
 * @param {}
 *            data
 */
var queryIndicatorsByPageCallback = function(data) {

	var currTable = $("#indicatortable");

	if (1 == CURR_PAGE) {
		// 清空
		$("tbody", currTable).empty();
	}
	for (var i = 0; i < data.length; i++) {
		var branchLevel = null != data[i].branch ? Math
				.ceil(data[i].branch / 3)
				+ " - " + data[i].level : "";
		var terminalAddr = (data[i].terminaladdr == undefined || data[i].terminaladdr == null)
				? ""
				: data[i].terminaladdr;

		var location = data[i].location;
		if (location.strLen() > 20 - 3) {
			location = location.substring(0, 20 - 3) + "...";
		}
		var tr = "<tr><td>" + data[i]._id + "</td><td>" + data[i].indicatoraddr
				+ "</td>" + "<td>" + terminalAddr + "</td><td>" + location
				+ "</td><td>" + data[i].phasetext + "</td><td>" + branchLevel
				+ "</td><td>" + data[i].time + "</td></tr>";
		$("tbody", currTable).append(tr);
	}

	// 刷新，关键重构是列与列头的关系
	currTable.table("refresh");

	$("tbody tr", currTable).bind("taphold", function() {
		backToolbar();

		CURR_DATA_TR = $(this);
		CURR_DATA_TR.addClass("tr-selected");

		$("#dataeditdiv")
				.html('<a data-role="button" id="modifybtn" data-icon="edit" data-inline="true" data-theme="f" data-iconpos="notext">修改</a>'
						+ '<a data-role="button" id="backbtn2" data-icon="back" data-inline="true" data-theme="f" data-iconpos="notext">取消</a>');
		$("a", "#dataeditdiv").trigger('create').buttonMarkup("refresh");

		$("#backbtn2", $("#dataeditdiv")).unbind().bind("tap", function() {
					CURR_DATA_TR.removeClass("tr-selected");
					CURR_DATA_TR = null;
					$(this).parent().html("");
				});
	});
}